package tmt.usercenter.web.service;

import com.tmt.helper.StringHelper;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tmt.usercenter.web.domain.SystemParam;
import tmt.usercenter.web.domain.enums.SystemParamCode;
import tmt.usercenter.web.repository.ISystemParamRepo;

import java.util.ArrayList;

@Service
@Transactional(rollbackFor = Exception.class)
public class SystemParamService extends TmtBaseService<SystemParam, Long> {

	@Getter
	private ISystemParamRepo systemParamRepo;

	@Autowired
	public SystemParamService(ISystemParamRepo systemParamRepo) {
		super(systemParamRepo, new ArrayList<>());
		this.systemParamRepo = systemParamRepo;
	}

	@Transactional(readOnly = true)
	public String getSystemParamValue(SystemParamCode code) {
		SystemParam sp = systemParamRepo.findByParamCode(code.name());
		String value = sp != null && !StringUtils.isEmpty(sp.getParamValue()) ? sp.getParamValue() : code.getParamValue();
		while (value.contains("{")) {
			int startIndex = value.indexOf("{");
			int endIndex = value.indexOf("}");
			String paramName = value.substring(startIndex + 1, endIndex);
			SystemParamCode spc = Enum.valueOf(SystemParamCode.class, paramName);
			String paramValue = getSystemParamValue(spc);
			value = value.replaceAll(String.format("\\{%s\\}", paramName), paramValue);
		}
		return value;
	}

	@Transactional(readOnly = true)
	public <T> T getSystemParamValue(SystemParamCode code, Class<T> clazz) {
		T t;
		try {
			String value = getSystemParamValue(code);
			t = StringHelper.convertTo(value, clazz);
		} catch (Exception ignored) {
			t = StringHelper.convertTo(code.getParamValue(), clazz);
		}
		return t;
	}

}
